$(function () {
    var playStatus = "pause";
    var playIndex;
    var timeArray = new Array();
    var i = 0;
    var songArray = new Array();
    var userId = 0;
    var $loop = 1;

    $.post("../user/login_status", function (data) {
        if ("no" != data) {
            userId = JSON.parse(data).id;
        } else {

        }

    });
    $.post("../music/list_player", function (data) {
        songlist(data);
        playListen();
    });

    // 利用ajax轮询监听播放列表是否发生变化
    var close = false;
    function playListen() {
        $.post("../music/player", "close="+close, function (data) {
            if (close == false) {
                songlist(data);
                playListen();
            }
        })
    }
    window.onunload = function (ev) {
        close = true;
    }

    function randomsort(a, b) {
        return Math.random()>.5 ? -1 : 1;
        //用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
    }

    $(".btn-big-loop").click(function () {
        switch ($loop) {
            case 1:
                $(this).attr("title", "列表播放");
                $loop = 2;
                break;
            case 2:
                $(this).attr("title", "单曲循环");
                $loop = 3;
                break;
            case 3:
                $(this).attr("title", "随机播放");
                $loop = 4;
                break;
            case 4:
                $(this).attr("title", "随机循环");
                $loop = 1;
                break;
            case 5:
                $(this).attr("title", "列表循环");
                $loop = 1;
                break;
        }
    })

    var thisPlay;
    var listId = new Array();
    function songlist(data) {
        $(".song-list-main").html(data).children("table").addClass("table");
        listId = new Array();
        $(".song-list-main tr[mid]").each(function (i, item) {
            listId[i] = $(item).attr("mid");
        })
        var items = listId.sort(randomsort);
        var itemsIndex = 0;
        $()
        $(".songlist-edit").click(function () {
            $(this).children("i").toggleClass("fa fa-check-square-o").toggleClass("fa fa-square-o");
        })
        $(".js-check-all").click(function () {
            $(".songlist-edit i").attr("class", $(this).children("i").attr("class"));
        })
        $(".song-list-main tr").unbind("hover").hover(function () {
            $(this).children(".songlist-songname").children("a").show();
        }, function () {
            $(this).children(".songlist-songname").children("a").hide();
        });
        $(".js-like").click(function () {
            if (userId == 0) {
                alert("尚未登录！");
            } else {
                //获取收藏对象的ID
                var likeId = $(this).parents("tr").attr("mid");
                userLike(likeId);
            }
        })

        $(".js-song-play").click(function () {
            thisPlay = $(this);
            var playId = thisPlay.parents("tr").attr("mid");
            for (var i in listId) {
                if (playId == listId[i]) {
                    playIndex = i;
                    break;
                }
            }
            var title;
            $.post("../music/play_song", "mid="+playId, function (song) {
                title = song.songName + "&nbsp;-&nbsp;";
                $(song.singers).each(function (i, e) {
                    title += e.singerName+"&nbsp;";
                    $(".action-singer").empty().append(e.singerName+"&nbsp;").attr("href", "../GetSingerDetaiServlet?opr=showDetail&singer_id="+e.singerId);      // 此处的链接还得更改
                });
                $(".progress-song-title").html(title);
                $("title").html("正在播放 "+title);
                $(".action-song").html(song.songName).attr("href", "song?id="+song.songId);     // 此处的链接还得更改
                $(".meta-info-album .action-album").html(song.album.albumName).attr("href", "album?id="+song.album.albumId);  // 此处的链接还得更改
                $(".song-info-cover img").attr("src", "../"+song.poster);
                $(".player-bg").css("background-image", "url(../"+song.poster+")");
                $("#jplayer_N").jPlayer("setMedia", {
                    title: title,
                    mp3: song.url
                })
                getLyricArray(song.lyric);
                $(".btn-big-play").unbind("click").click(ActionPlay);
                $(".btn-big-prev").unbind("click").click(function () {
                    if (playIndex == 0) {
                        $(".song-list-main tr[mid="+listId[listId.length-1]+"]").find(".js-song-play").click();
                    } else {
                        $(".song-list-main tr[mid="+listId[playIndex-1]+"]").find(".js-song-play").click();
                    }
                    // thisPlay.parents("tr").prev().find(".js-song-play").click();
                })
                $(".btn-big-next").unbind("click").click(function () {
                    if (playIndex == listId.length - 1) {
                        $(".song-list-main tr[mid="+listId[0]+"]").find(".js-song-play").click();
                    } else {
                        $(".song-list-main tr[mid="+listId[parseInt(playIndex)+1]+"]").find(".js-song-play").click();
                    }
                })
                $(".btn-big-like").unbind("click").click(function () {
                    if (userId == 0) {
                        alert("请登录后再操作");
                    } else {
                        userLike(listId[i]);
                    }
                })
                $(".btn-big-download").unbind("click").click(function () {
                    if (userId == 0) {
                        alert("请登录后再操作");
                    } else {
                        userDownload([{"mid":listId[i]}]);
                    }
                })
                $(".btn-big-comment").attr("href", "song?id="+listId[playIndex]+"#comment");

                $("#jplayer_N").bind($.jPlayer.event.ended, function(event) {
                    switch ($loop) {
                        case 1:
                            $(".btn-big-next").click();
                            break;
                        case 2:
                            if (playIndex < listId.length - 1) {
                                $(".btn-big-next").click();
                            }
                            break;
                        case 3:
                            $("#jplayer_N").jPlayer("play");
                            break;
                        case 4:
                            if (itemsIndex < items.length) {
                                $(".song-list-main tr[mid="+items[itemsIndex]+"]").find(".js-song-play").click();
                                itemsIndex++;
                            }
                            break;
                        case 5:
                            $(".song-list-main tr[mid="+items[itemsIndex]+"]").find(".js-song-play").click();
                            if (itemsIndex < items.length) {
                                itemsIndex++;
                            } else if (itemsIndex = items.length) {
                                itemsIndex = 0;
                            }
                            break;
                    }
                });
                $("#jplayer_N").jPlayer("play");
            }, "JSON");
        })
    }

    $(".js-big-like").click(function () {
        var midArr = listChoose();
        if (midArr.length == 0) {
            alert("请选择操作的歌曲");
        } else if (userId == 0) {
            alert("请登录");
        } else {
            for (var i in midArr) {
                userLike(midArr[i]);
            }
        }
    })
    
    $(".js-download").click(function () {
        var midArr = listChoose();
        if (midArr.length == 0) {
            alert("请选择操作的歌曲");
        } else if (userId == 0) {
            alert("请登录");
        } else {
            var arr = new Array();
            for (var i in midArr) {
                arr[i] = {"mid" : midArr[i]};
            }
            userDownload(arr);
        }
    })

    $(".js-delete").click(function () {
        var midArr = listChoose();
        if (midArr.length == 0) {
            alert("请选择操作的歌曲");
        } else {
            $.post("../music/remove_player", {"data":JSON.stringify(midArr)}, function (data) {
                songlist(data);
            })
        }
    })

    $(".js-deleted").click(function () {
        if (confirm("确定要清空列表？") == true) {
            $.post("../music/remove_player", "data=all", function (data) {
                songlist(data);
                $("#jplayer_N").jPlayer("stop");
                $("title").html("魔音云音乐");
                $(".song-info-cover img").attr("src", "../images/album/player_cover.png");
                $(".song-lyric-box").empty();
                $(".progress-song-title").empty();
                $(".jp-current-time").empty();
                $(".jp-duration").empty();
            })
        } 
    })

    function userLike(likeId) {
        //获取收藏类型ID
        var likeType = 1;
        $.ajax({
            "url": "../UserLikeServlet",
            "data": "likeId=" + likeId + "&userId=" + userId + "&likeType=" + likeType,
            "type": "GET",
            "dataType": "json",
            "success": function (result) {
                if (result.data == "YES") {
                    alert("收藏成功");
                } else if (result.data == "NO") {
                    alert("取消收藏成功");
                } else {
                    alert("操作异常，请稍后重试");
                }
            }
        })
    }

    function userDownload(mid) {
        $.post("../user/download", {"data":JSON.stringify(mid)}, function (data) {
            var songArr = JSON.parse(data);
            for (var i in songArr) {
                var $a = document.createElement("a");
                $a.setAttribute("href", songArr[i].url);
                $a.setAttribute("download", songArr[i].songName+".mp3");
                $a.click();
            }
        })
    }

    function listChoose() {
        var midArr = new Array();
        $(".songlist-edit i[class*=fa-check-square-o]").each(function (index, element) {
            midArr[index] = $(this).parents("tr").attr("mid");
        })
        return midArr;
    }

    function timeUpdate(e) {
        var currentTime = e.jPlayer.status.currentTime;
        if (currentTime > timeArray[i] && currentTime < timeArray[i+1]) {
            activeLyric(i);
            moveLyric(i);
            if (i < timeArray.length - 1) {
                i++;
            } else {
                i = 0;
            }
        } else if (currentTime > timeArray[timeArray.length-1]) {
            activeLyric(timeArray.length);
            moveLyric(timeArray.length);
        } else if (currentTime < timeArray[0]) {
            activeLyric(0);
            moveLyric(0);
        } else {
            for (var j in timeArray) {
                if (currentTime < timeArray[j]) {
                    i = j;
                    activeLyric(j-1);
                    moveLyric(j-1);
                    break;
                }
            }
        }
    }
    /*var songArray = [
        { title: "方圆几里", mp3: "../media/1.mp3", sid:"2", lyric:"lyric/方圆几里.lrc", index:0 },
        { title: "晴天-周杰伦", mp3: "http://dl.stream.qqmusic.qq.com/M5000039MnYb0qxYhV.mp3?vkey=10F8B1E6753CFF302762EBB3F44EDE25B4806AD9F3BD6F447B1912002EB94A013F7F873F6450397EB18A545C000CE3942EB724CE1C8E8C95&guid=5150825362&fromtag=1", sid:"3", lyric:"lyric/晴天-周杰伦.lrc", index:1 },
        { title: "身骑白马", mp3: "http://fs.open.kugou.com/91d721edc2c6a953514fa321a1052a01/5c7405f2/G009/M01/19/18/qYYBAFUJpcqAeam8AEx_q5hVODk464.mp3", sid:"1", lyric:"lyric/2.lrc", index:2 },
    ];*/

    $("#jplayer_N").jPlayer({
        cssSelectorAncestor: "#jp_container_N",
        swfPath: "jPlayer",
        supplied: "mp3",
        useStateClassSkin: true,    // 必须加上，否则无法中途暂停和取消静音
        keyEnabled: true,
        keyBindings: {
            play: {
                key: 32,
                fn: function(f) {
                    if(f.status.paused) {
                        f.play();
                    } else {
                        f.pause();
                    }
                }
            }
        },
        remainingDuration: false,
        autoPlay: false,
        timeupdate: function (e) {
            timeUpdate(e);
        },
        play: function (e) {
            $(".btn-big-play").find(".fa-circle").next().toggleClass("fa-play").toggleClass("fa-pause");
            $(".progress-dot").css("animation", "progress-dot-animation 1.5s ease-in-out infinite");
        },
        pause: function (e) {
            $(".btn-big-play").find(".fa-circle").next().toggleClass("fa-play").toggleClass("fa-pause");
            $(".progress-dot").css("animation", "");
        },
    })
    
    $(".btn-big-loop").click(function () {

    })

    // 触发播放/暂停事件时调用的方法，待补全
    function ActionPlay() {
        if (playStatus == "pause") {
            $("#jplayer_N").jPlayer("play");
            playStatus = "play";
        } else {
            $("#jplayer_N").jPlayer("pause");
            playStatus = "pause";
        }
    }

    function getLyricArray(lrc) {
        var lycArr = lrc.split("\n");
        timeArray = new Array();
        var j = 0;
        $(".song-lyric-inner").empty();
        for (var i in lycArr) {
            var time = lycArr[i].split("]")[0].substring(1);
            if (!time.charAt(0).match("[0-9]")) {
                continue;
            }
            timeArray[j] = (time.split(":")[0] * 60 + parseFloat(time.split(":")[1])).toFixed(3);
            $(".song-lyric-inner").append("<p index='"+j+"'>"+lycArr[i].split("]")[1]+"</p>");
            j++;
        }
        var lyricWheel = 0;
        $(".song-lyric-inner").unbind("mousewheel").bind("mousewheel", function (event, delta) {
            if (event.originalEvent.deltaY > 0) {
                lyricWheel -= 30;
            } else if (event.originalEvent.deltaY < 0) {
                lyricWheel += 30;
            }
            var lyricHeight = $(this).height() - $(this).parent().height();
            if (lyricWheel > 0) {
                lyricWheel = 0;
            } else if (lyricWheel < -lyricHeight) {
                lyricWheel = -lyricHeight;
            }
            $(this).css("transform", "translateY("+lyricWheel+"px)");
        })
        $("#jplayer_N").jPlayer.timeupdate = function (e) {
            timeUpdate(e);
        }
    }

    function moveLyric(i) {
        var lyricTrans = 75;
        for (var k = 0; k < i; k++) {
            if ($(".song-lyric-inner p[index="+k+"]").height() == 26) {
                lyricTrans -= 25;
            } else {
                lyricTrans -= $(".song-lyric-inner p[index="+k+"]").height();
            }
        }
        $(".song-lyric-inner").css("transform", "translateY("+lyricTrans+"px)");
    }
    function activeLyric(i) {
        $(".song-lyric-inner").find("p[index="+i+"]").addClass("lyric-active");
        $(".song-lyric-inner").find("p[index!="+i+"]").removeClass("lyric-active");
    }

})